package com.mall.utils;


import cn.hutool.core.convert.Convert;
import com.mall.vo.UmsMenuVo;

import java.util.ArrayList;
import java.util.List;

public class TreeListUtil {
    public static List<UmsMenuVo> buildTree(List<UmsMenuVo> entities) {

        // 最终输出树结构list集合e
        List<UmsMenuVo> returnList = new ArrayList<>();

        // 存放所有id集合
        List<Long> tempList = new ArrayList<>();
        for (UmsMenuVo entity : entities) {
            tempList.add(entity.getId());
        }

        // 遍历循环实体表list集合
        for (UmsMenuVo entity : entities) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(entity.getParentId())) {
                recursionFunction(entities, entity);
                returnList.add(entity);
            }
        }
        if (returnList.isEmpty()) {
            returnList = entities;
        }
        return returnList;
    }

    /**
     * 递归遍历
     */
    private static void recursionFunction(List<UmsMenuVo> entities, UmsMenuVo entity) {
        // 得到子节点列表
        List<UmsMenuVo> childList = getChildList(entities, entity);
        entity.setChildren(childList);
        for (UmsMenuVo tChild : childList) {
            if (hasChild(entities, tChild)) {
                recursionFunction(entities, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private static List<UmsMenuVo> getChildList(List<UmsMenuVo> entities, UmsMenuVo entity) {
        List<UmsMenuVo> arrayList = new ArrayList<>();
        for (UmsMenuVo n : entities) {
            if (null != n.getParentId() && n.getParentId().longValue() == entity.getId().longValue()) {
                arrayList.add(n);
            }
        }
        return arrayList;
    }

    /**
     * 判断是否有下级节点
     */
    private static boolean hasChild(List<UmsMenuVo> list, UmsMenuVo t) {
        return getChildList(list, t).size() > 0;
    }
}
